package com.dapeis.web.wx.spring.handler;


import java.sql.SQLException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import com.ag.core.exception.CodeException;
import com.ag.utils.json.AGsonBuilder;
import com.dapeis.core.utils.StylistConstants;
import com.dapeis.exception.Code;
/**
 * 
 * title: ApiCodeExceptionHandler.java 
 * 异常句柄
 *
 * @author rplees
 * @email rplees.i.ly@gmail.com
 * @version 1.0  
 * @created 2015年9月16日 下午3:40:35
 */
@Controller
public class ExceptionHandler implements HandlerExceptionResolver {
	
	private ModelAndView mv(Object handler, Map<String, Object> map,HttpServletRequest request, Exception ex) {
		
		Enumeration<String> headerNames = request.getHeaderNames();
		Map<String, String> headerMap = new HashMap<String, String>();
		while (headerNames.hasMoreElements()) {
			String nextElement = headerNames.nextElement();
			headerMap.put(nextElement, request.getHeader(nextElement));
		}
		
		//记录logger
		StylistConstants.Loggers.EXCEPTION.info("请求地址:{},参数：{},发生异常:{}, header:{}",
		new Object[] {
			request.getRequestURI(),
			AGsonBuilder.create().toJsonTree(request.getParameterMap()).toString(), 
			ex.toString(),
			AGsonBuilder.create().toJsonTree(headerMap).toString(), 
		});
		
		if(ex instanceof CodeException) {
			
		} else {
			ex.printStackTrace();
		}
		return new ModelAndView(new MappingJackson2JsonView(), map);
	}
	
	@Override
	public ModelAndView resolveException(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex) {
		
		if(ex instanceof CodeException) {//自定义异常
			CodeException ce = (CodeException) ex;
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("code", ce.getCode());
			map.put("msg", ce.getMsg());
			map.put("succ", false);
			return mv(handler, map, request, ex);
		} else if(ex instanceof SQLException || ex instanceof DataAccessException){
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("code", Code.SQL_EXCEPTION);
			map.put("msg", "数据库操作失败");
			map.put("succ", false);
			return mv(handler, map, request, ex);
		} else {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("code", -1);
			map.put("msg", ex.getLocalizedMessage());
			map.put("succ", false);
			
			return mv(handler, map, request, ex);
		}
	}

}
